package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.device;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import com.cqhilink.api.common.utils.HttpClientUtil;import com.cqhilink.api.common.utils.UniqueUtil;import com.cqhilink.api.common.utils.date.DateStyle;import com.cqhilink.api.common.utils.date.DateUtil;import com.cqhilink.api.common.utils.enums.RespCodeEnum;import com.cqhilink.iot.jobstandardmanagement.facade.utils.BackMessage;import com.cqhilink.iot.jobstandardmanagement.common.enums.DeviceStateEnum;import com.cqhilink.iot.jobstandardmanagement.facade.utils.DeviceStatus;import com.cqhilink.iot.jobstandardmanagement.facade.utils.TreeIconSkin;import com.cqhilink.iot.jobstandardmanagement.dao.mapper.*;import com.cqhilink.iot.jobstandardmanagement.facade.model.*;import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmDeviceMaintenanceService;import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmDeviceParamerService;import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmDeviceService;import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmDeviceValidateCycleService;import com.cqhilink.iot.jobstandardmanagement.facade.service.entity.JsmEntityService;import com.cqhilink.iot.jobstandardmanagement.facade.service.organization.JsmOrganizationService;import com.cqhilink.iot.jobstandardmanagement.facade.service.reportinfoItem.JsmReportinfoItemService;import com.google.common.collect.Maps;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import java.math.BigDecimal;import java.text.SimpleDateFormat;import java.util.*;/** * @Description: (生产设备服务层实现类) * @author: YuPeng * @date: 2016/12/2,16:15 * modify by huangxueqian * @date: */public class JsmDeviceServiceImpl implements JsmDeviceService {    public Logger logger = LoggerFactory.getLogger(this.getClass());    @Autowired    private DeviceMapper deviceMapper;    @Autowired    private OrganizationMapper orgMapper;    @Autowired    private OrgAreaMapper orgAreaMapper;    @Autowired    private FileMapper fileMapper;    @Autowired    private EntityTypeMapper entityTypeMapper;    @Autowired    private EntityTypeProMapper entpProMapper;    @Autowired    private EntityProMapper entityProMapper;    @Autowired    private ManufactorMapper manuMapper;    @Autowired    private JsmEntityService entityService;    @Autowired    private JsmOrganizationService organizationService;    @Autowired    private EntityMapper entityMapper;    @Autowired    private JsmDeviceParamerService jsmDeviceParamerService;    //维保周期    @Autowired    private JsmDeviceMaintenanceService jsmDeviceMaintenanceService;    @Autowired    private JsmReportinfoItemService reportinfoItemService;    @Autowired    private DeviceExpandMapper deviceExpandMapper;    @Autowired    private DeviceRecordMapper deviceRecordMapper;    @Autowired    private JsmDeviceValidateCycleService jsmDeviceValidateCycleService ;    @Value("#{configProperties['opc_url']}")    private String configUril;    /**     * 按组织机构id查询设备list     * @param orgId     * @return     */    @Override    public List<DeviceVO> getDevices(String orgId) {        return StringUtils.isBlank(orgId) ? null : deviceMapper.selectByPOId(orgId);    }    /**     * 添加设备     *     * @param device 设备实体     * @return     * @throws Exception     */    @Override    @Transactional(readOnly = false)    public Map<String, Object> addDevice(Device device, EmployeeVo employee) throws Exception {        Map<String, Object> map = new HashMap<>();        try {            String creatorId = employee.getEmployeeId();            String deviceId = UniqueUtil.uuid();            device.setDeviceId(deviceId);            device.setCreateId(creatorId);            device.setStatus(0);            device.setCreateTime(DateUtil.getTimeString());            device.setModifyId(creatorId);            device.setModifyTime(DateUtil.getTimeString());            //保存设备图片            if (StringUtils.isNotEmpty(device.getUploadFiles())) {                List<File> uploadFiles = JSON.parseArray(device.getUploadFiles(), File.class);                // 文档上传文件                if (uploadFiles != null && uploadFiles.size() > 0) {                    for (File file : uploadFiles) {                        file.setBusinessId(deviceId);                        file.setFileId(UniqueUtil.uuid());                        fileMapper.insertSelective(file);                    }                }            }            //保存设备信息            jsmDeviceValidateCycleService.operateValidateCycle(device);            deviceMapper.insert(device);            //同步生产实体            addEntity(device, creatorId, employee);            // 新增设备参数到特性值表去            if (device.getDeviceParamers() != null && device.getDeviceParamers().size() > 0) {                jsmDeviceParamerService.insertDeviceParamers(deviceId, device.getDeviceParamers(), employee);            }            // 维保周期保存            if (device.getDeviceMaintenances() != null && device.getDeviceMaintenances().size() > 0) {                jsmDeviceMaintenanceService.insertDeviceMaintenances(device, device.getDeviceMaintenances(), employee);            }            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.ADD_OK);            return map;        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException("保存设备信息发生错误");        }    }    /**     * 同步设备信息到实体     *     * @param device     * @param creatorId     */    private void addEntity(Device device, String creatorId, Employee employee) {        //同步设备信息到实体信息        Entity entity = new Entity();        entity.setEnId(device.getDeviceId());        entity.setDeviceId(device.getDeviceId());        entity.setParentOrgId(device.getOrgId());        entity.setEnName(device.getDeviceName());        entity.setEnTypeId(device.getEntityTypeId());        entity.setParentEnId(device.getParentDeviceId());        entity.setCreatorId(creatorId);        entity.setStatus(0);        entity.setCreateTime(DateUtil.getTimeString());        entity.setModifierId(creatorId);        entity.setModifyTime(DateUtil.getTimeString());        entityMapper.insert(entity);        //新增特性信息        for (EntityPro entityPro : device.getEntityPros()) {            // 是否存在特性值Id=""            entityPro.setDeviceId(entity.getEnId());            entityPro.setEntityId(entity.getEnId());            entityPro.setCreator(creatorId);            entityPro.setStatus(new BigDecimal(0));            entityPro.setEntityTypeId(entity.getEnTypeId());            entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));            entityPro.setModifyer(creatorId);            entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));            entityPro.setDevicePropertyId(UniqueUtil.uuid16());            entityProMapper.insertSelective(entityPro);            try {                EmployeeVo employeeVo = JSON.parseObject(JSON.toJSONString(employee), EmployeeVo.class);                reportinfoItemService.insertPropertyMap(entityPro, employeeVo);            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 按id删除设备     *     * @param id     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceById(String id) throws Exception {        Map<String, Object> map = new HashMap<>();        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        if (!StringUtils.isBlank(id) && deviceMapper.updateStatusByDeviceId(1, id) > 0) {            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.DEL_OK);            return map;        }        map.put("msg", BackMessage.DEL_FAIL);        return map;    }    /**     * 按id批量删除设备     *     * @param ids     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceById(String[] ids) throws Exception {        List<String> idss = new ArrayList<>();        for (int i = 0; i < ids.length; i++) {            idss.add(ids[i]);        }        Map<String, Object> map = new HashMap<>();        map.put("list", idss);        map.put("status", 1);        if (deviceMapper.updateStatusByDeviceIds(map) > 0) {            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.DEL_OK);            return map;        }        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        map.put("msg", BackMessage.DEL_FAIL);        return map;    }    /**     * 将设备状态设置为入库状态     *     * @param id     * @return     */    public boolean stockDevice(String id) {        if (!StringUtils.isBlank(id) && deviceMapper.updateStatusByDeviceId(0, id) > 0)            return RespCodeEnum.RESP_CODE_ENUM_true.code();        return RespCodeEnum.RESP_CODE_ENUM_false.code();    }    /**     * 将设备状态设置为启用状态     *     * @param id     * @return     */    public boolean ableDevice(String id) {        if (!StringUtils.isBlank(id) && deviceMapper.updateStatusByDeviceId(1, id) > 0)            return RespCodeEnum.RESP_CODE_ENUM_true.code();        return RespCodeEnum.RESP_CODE_ENUM_false.code();    }    /**     * 将设备状态设置为删除状态     *     * @param id     * @return     */    public boolean disableDevice(String id) {        if (!StringUtils.isBlank(id) && deviceMapper.updateStatusByDeviceId(2, id) > 0)            return RespCodeEnum.RESP_CODE_ENUM_true.code();        return RespCodeEnum.RESP_CODE_ENUM_false.code();    }    /**     * 修改设备信息     *     * @param device     * @return     * @throws Exception     */    @Override    @Transactional(readOnly = false)    public Map<String, Object> modifyDevice(Device device, EmployeeVo employee) throws Exception {        Map<String, Object> map = new HashMap<>();        try {            //设备基本信息            String modifyId = employee.getEmployeeId();            device.setModifyId(modifyId);            device.setModifyTime(DateUtil.getTimeString());            if (StringUtils.isNotEmpty(device.getUploadFiles())) {                List<File> uploadImgs = JSON.parseArray(device.getUploadFiles(), File.class);                //上传图片                if (uploadImgs != null && uploadImgs.size() > 0) {                    for (File upFile : uploadImgs) {                        upFile.setBusinessId(device.getDeviceId());                        upFile.setFileId(UniqueUtil.uuid());                        fileMapper.insertSelective(upFile);                    }                }            }            if (StringUtils.isNotEmpty(device.getDeletedFiles())) {                List<File> delimgs = JSON.parseArray(device.getDeletedFiles(), File.class);                //删除不要的图片                if (delimgs != null && delimgs.size() > 0) {                    for (File delFile : delimgs) {                        fileMapper.deleteByPrimaryKey(delFile.getFileId());                    }                }            }            // 周期校验            jsmDeviceValidateCycleService.operateValidateCycle(device);            // 设备更新            deviceMapper.update(device);            //同步设备信息到实体信息            Entity entity = new Entity();            entity.setEnId(device.getDeviceId());            List<EntityVO> entityVOs = entityMapper.selectByEntity(entity);            if (entityVOs != null && entityVOs.size() > 0) {//修改                modifyEntity(entityVOs.get(0), entity, device, employee);            } else {//新增                addEntity(device, modifyId, employee);            }            if (device.getDeviceParamers() != null && device.getDeviceParamers().size() > 0) {                jsmDeviceParamerService.delDeviceParamers(device, employee);                jsmDeviceParamerService.insertDeviceParamers(device.getDeviceId(), device.getDeviceParamers(), employee);            }            // 维保周期保存            if (device.getDeviceMaintenances() != null && device.getDeviceMaintenances().size() > 0) {                jsmDeviceMaintenanceService.delDeviceMaintenances(device);                jsmDeviceMaintenanceService.insertDeviceMaintenances(device, device.getDeviceMaintenances(), employee);            } else {                jsmDeviceMaintenanceService.delDeviceMaintenances(device);            }            // 设置校验周期            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.ADD_OK);            return map;        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException("修改设备信息出错");        }    }    /**     * 同步修改实体信息     *     * @param entityVO     * @param entity     实体id     * @param device     设备id     * @param employeeVo 修改人id , 可以通过获取当前人进行查询     */    private void modifyEntity(EntityVO entityVO, Entity entity, Device device, EmployeeVo employeeVo) {        entity.setEnId(entityVO.getEnId());        entity.setDeviceId(device.getDeviceId());        entity.setParentOrgId(device.getOrgId());        entity.setEnName(device.getDeviceName());        entity.setEnTypeId(device.getEntityTypeId());        entity.setModifierId(employeeVo.getEmployeeId());        entity.setModifyTime(DateUtil.getTimeString());        entityMapper.update(entity);        if (device.getEntityPros() != null && device.getEntityPros().size() > 0) {            for (EntityPro entityPro : device.getEntityPros()) {                if (entityPro.getDevicePropertyId() != null) {                    entityPro.setModifyer(employeeVo.getEmployeeId());                    entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    if (entityPro.getMaxValue() != null) {                        entityPro.setMaxValue(entityPro.getMaxValue());                    }                    if (entityPro.getMinValue() != null) {                        entityPro.setMinValue(entityPro.getMinValue());                    }                    try {                        reportinfoItemService.insertPropertyMap(entityPro, employeeVo);                    } catch (Exception e) {                        logger.info(e.getLocalizedMessage());                    }                    entityProMapper.updateByPrimaryKeySelective(entityPro);                } else {                    entityPro.setDevicePropertyId(UniqueUtil.uuid16());                    entityPro.setDeviceId(entity.getEnId());                    entityPro.setEntityId(entity.getEnId());                    entityPro.setCreator(employeeVo.getEmployeeId());                    entityPro.setStatus(new BigDecimal(0));                    if (entityPro.getMaxValue() != null) {                        entityPro.setMaxValue(entityPro.getMaxValue());                    }                    if (entityPro.getMinValue() != null) {                        entityPro.setMinValue(entityPro.getMinValue());                    }                    entityPro.setEntityTypeId(entity.getEnTypeId());                    entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    entityPro.setModifyer(employeeVo.getEmployeeId());                    entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    try {                        reportinfoItemService.insertPropertyMap(entityPro, employeeVo);                    } catch (Exception e) {                        logger.info(e.getLocalizedMessage());                    }                    entityProMapper.insertSelective(entityPro);                }            }        }        if (device.getEntityPros() != null && device.getEntityPros().size() > 0) {            for (EntityPro entityPro : device.getEntityPros()) {                if (entityPro.getDevicePropertyId() != null) {                    entityPro.setModifyer(employeeVo.getEmployeeId());                    entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    if (entityPro.getMaxValue() != null) {                        entityPro.setMaxValue(entityPro.getMaxValue());                    }                    if (entityPro.getMinValue() != null) {                        entityPro.setMinValue(entityPro.getMinValue());                    }                    entityProMapper.updateByPrimaryKeySelective(entityPro);                } else {                    entityPro.setDevicePropertyId(UniqueUtil.uuid16());                    entityPro.setDeviceId(entity.getEnId());                    entityPro.setEntityId(entity.getEnId());                    entityPro.setCreator(employeeVo.getEmployeeId());                    entityPro.setStatus(new BigDecimal(0));                    if (entityPro.getMaxValue() != null) {                        entityPro.setMaxValue(entityPro.getMaxValue());                    }                    if (entityPro.getMinValue() != null) {                        entityPro.setMinValue(entityPro.getMinValue());                    }                    entityPro.setEntityTypeId(entity.getEnTypeId());                    entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    entityPro.setModifyer(employeeVo.getEmployeeId());                    entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                    entityProMapper.insertSelective(entityPro);                }            }        }        // 删除特性值问题        if (device.getDelEntityPros() != null && device.getDelEntityPros().size() > 0) {            for (EntityPro entityPro : device.getDelEntityPros()) {                if (StringUtils.isNotEmpty(entityPro.getDevicePropertyId())) {                    entityProMapper.deleteByPrimaryKey(entityPro.getDevicePropertyId());                }            }        }    }    /**     * @param entityPro     * @param employee     */    public Integer syncDeviceProperty(EntityPro entityPro, Employee employee, Device device) {        int resInt = 0;        Organization organization = organizationService.selectOrgByOrgId(employee.getOrgId());        DeviceVO queryDevice = new DeviceVO();        queryDevice.setEntityTypeId(device.getEntityTypeId());        queryDevice.setOrgId(organization.getOrgId());        List<DeviceVO> deviceVOs = deviceMapper.selectDeviceListByOrgId(queryDevice);        if (deviceVOs != null && deviceVOs.size() > 0) {            for (DeviceVO deviceVO1 : deviceVOs) {                entityPro.setDevicePropertyId(UniqueUtil.uuid16());                entityPro.setEntityId(deviceVO1.getDeviceId());                entityPro.setDeviceId(deviceVO1.getDeviceId());                entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                entityPro.setModifyer(employee.getEmployeeId());                entityPro.setStatus(new BigDecimal(0));                resInt = resInt + entityProMapper.insertSelective(entityPro);            }        }        return resInt;    }    /**     * 按主键ID查询设备信息     *     * @param id     * @return     * @throws Exception     */    @Override    public DeviceVO getDeviceById(String id) throws Exception {        DeviceVO device = deviceMapper.selectByDeviceId(id);        // 查询 特性值        List<EntityPro> entityProList = entityProMapper.getEntityProByEntityId(device.getDeviceId());        if (entityProList != null && entityProList.size() > 0) {            device.setEntityPros(entityProList);        }        // 查询其他参数        DeviceParamer deviceParamer = new DeviceParamer();        deviceParamer.setDeviceId(device.getDeviceId());        List<DeviceParamer> deviceParamers = jsmDeviceParamerService.getDeviceParamers(deviceParamer);        if (deviceParamers != null && deviceParamers.size() > 0) {            device.setDeviceParamers(deviceParamers);        }        DeviceMaintenance deviceMaintenance = new DeviceMaintenance();        deviceMaintenance.setDeviceId(device.getDeviceId());        List<DeviceMaintenance> deviceMaintenances = jsmDeviceMaintenanceService.getDeviceMaintenanceList(deviceMaintenance);        device.setDeviceMaintenances(deviceMaintenances);        // 查询设备校验周期        List<DeviceValidateCycle>  deviceValidateCycleList = jsmDeviceValidateCycleService.queryDeviceValidateCycleList(device.getDeviceId());        device.setDeviceValidateCycleList(deviceValidateCycleList);        return device;    }    /**     * 按多条件搜索设备list     *     * @param deviceVO     * @return     * @throws Exception     */    @Override    public Map<String, Object> searchDevices(DeviceVO deviceVO) throws Exception {        Map<String, Object> map = new HashMap<>();//        List<String> orgIds = Lists.newArrayList();//        Organization organization = orgMapper.selectOrgByOrgId(deviceVO.getOrgId());//        if (organization != null) {//            orgIds.add(organization.getOrgId());//            if (organization != null) {//                List<Organization> children = orgMapper.selectOrgByOrgPId(organization.getOrgId());//                if (children == null || children.size() <= 0) {//                    orgIds.add(organization.getOrgId());//                } else {//                    getChidrenOrgIds(children, orgIds);//                }//            }//            deviceVO.setOrgIds(orgIds);//        } else {//            deviceVO.setParentDeviceId(deviceVO.getOrgId());//        }        List<DeviceVO> deList = deviceMapper.selectByDim(deviceVO);        map.put("total", deviceMapper.selectCountByDim(deviceVO));        map.put("rows", deList);        return map;    }    /**     * 得到所有的子孩子(组织)     *     * @param children     * @param retList     */    private void getChidrenOrgIds(List<Organization> children, List<String> retList) {        for (Organization organization : children) {            retList.add(organization.getOrgId());            List<Organization> chil = orgMapper.selectOrgByOrgPId(organization.getOrgId());            if (chil != null && chil.size() > 0) {                getChidrenOrgIds(chil, retList);            }        }    }    /**     * 私有方法     * 批量将设备信息进行填充完整，附加组织机构/实体类别等信息     *     * @param deList     * @return     */    private List<DeviceVO> transToFull(List<DeviceVO> deList) {        List<DeviceVO> list = new ArrayList<>();        for (DeviceVO device : deList) {            transToFull(device);            list.add(device);        }        return list;    }    /**     * 私有方法     * 将设备信息进行填充完整，附加组织机构/实体类别等信息     *     * @param device 设备信息     * @return     */    private void transToFull(DeviceVO device) {        if (device.getOrgId() != null) {            Organization org = orgMapper.selectOrgByOrgId(device.getOrgId());            device.setOrg(org);            device.setOrgName(org.getOrgName());        }        device.setInTime(DateUtil.formatDate(device.getInTime()));        device.setInUseTime(DateUtil.formatDate(device.getInUseTime()));        device.setCreateTime(DateUtil.formatDate(device.getCreateTime()));        device.setModifyTime(DateUtil.formatDate(device.getModifyTime()));        if (device.getAreaId() != null) {            OrgAreaVo orgArea = orgAreaMapper.selectByPrimaryKey(device.getAreaId());            device.setOrgArea(orgArea);            device.setOrgAreaName(orgArea.getAreaName());        }        if (device.getEntityTypeId() != null) {            EntityType enType = entityTypeMapper.selectByPrimaryKey(device.getEntityTypeId());            device.setEntityType(enType);            device.setEnTypeName(enType.getEntityTypeName());        }        if (device.getManuId() != null) {            Manufactor manufactor = manuMapper.selectByPrimaryKey(device.getManuId());            device.setManufactor(manufactor);            device.setEnTypeName(manufactor.getManuName());        }        List<File> imgs = fileMapper.queryByBusinessId(device.getDeviceId());        device.setImgs(imgs);        for (DeviceStatus deviceStatus : DeviceStatus.values()) {            if (device.getStatus() == Integer.parseInt(deviceStatus.getCode())) {                device.setStatusName(deviceStatus.getDesc());            }        }    }    /*    -----------------------------以下为设备特性操作方法--------------------------------------------------------------------------------------     */    /**     * 获取设备特性     *     * @param device     * @return     */    @Override    public Map<String, Object> getDevicePro(Device device) throws Exception {        Map<String, Object> map = new HashMap<>();        //添加分页查询条件        if (device.getOffset() == null) device.setOffset(0);        if (device.getLimit() == null) device.setLimit(10);        List<EntityPro> proList = entityProMapper.selectByDevice(device);        Integer total = entityProMapper.selectCountByDevice(device);        if (proList != null && proList.size() > 0) {            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("total", total);            map.put("rows", proList);            return map;        }        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        map.put("msg", "该设备还没有特性！");        return map;    }    /**     * 从生产实体类型特性中克隆到所属设备特性中     *     * @param entityId 实体ID     * @throws Exception 根据实体ID， 查询生产实体类型，根据生产实体类型查询，生产实体类型特性值，然后将生产实体类型特性值，插入到实体特性值     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> clonePro(String entityId, EmployeeVo employee) throws Exception {        Map<String, Object> resMap = new HashMap<>();        Entity entity = entityService.findEntity(entityId);        if (entity == null) {            resMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());            resMap.put("msg", "实体不存在!");        } else {            List<EntityTypePro> entityTypePList = entpProMapper.selectByEnTypeId(entity.getEnTypeId());            if (entityTypePList == null) {                resMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());                resMap.put("msg", "设备类型特性值！");            } else {                for (EntityTypePro entityTypePro : entityTypePList) {                    EntityPro entityPro = new EntityPro();                    entityPro.setEntityId(entityId);                    entityPro.setEntpPropertyId(entityTypePro.getDevicePropertyId());                    entityPro.setStatus(BigDecimal.valueOf(0D));                    /**                     * 遍历特性                     * 实体特性是否已经存在，已经存在则，不进行复制，如不存在则进行插入操作                     */                    EntityPro entityProIs = entityProMapper.selectByEntityPro(entityPro);                    if (entityProIs == null) {                        /**                         *插入特性值                         */                        entityPro.setDevicePropertyId(UniqueUtil.uuid16());                        if (entityTypePro.getPropertyName() != null)                            entityPro.setPropertyName(entityTypePro.getPropertyName());                        if (entityTypePro.getPropertyValue() != null)                            entityPro.setPropertyValue(entityTypePro.getPropertyValue());                        if (entityTypePro.getPropertyUnit() != null)                            entityPro.setPropertyUnit(entityTypePro.getPropertyUnit());                        entityPro.setEntpPropertyId(entityTypePro.getDevicePropertyId());                        entityPro.setEntityTypeId(entity.getEnTypeId());                        entityPro.setPropertyType(entityTypePro.getPropertyType());                        entityPro.setEntityId(entityId);                        entityPro.setStatus(entityTypePro.getStatus());                        entityPro.setCreator(employee.getEmployeeId());                        entityPro.setModifyer(employee.getEmployeeId());                        entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                        entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));                        entityProMapper.insertSelective(entityPro);                    }                }                resMap.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());                resMap.put("msg", "实体特性克隆成功！");            }        }        return resMap;    }    /**     * 根据组织ID和设备类型ID查询     *     * @param deviceVO     * @throws Exception     */    @Override    public Map<String, Object> findParamList(DeviceVO deviceVO) throws Exception {        Map<String, Object> resMap = new HashMap<>();        if (StringUtils.isEmpty(deviceVO.getOrgId()) || StringUtils.isEmpty(deviceVO.getEntityTypeId())) {            return resMap;        }        resMap.put("rows", deviceMapper.findParamList(deviceVO));        return resMap;    }    /**     * 将生产实体类型特性转换为设备特性并添加到数据库中     *     * @param proList     * @param device     */    private void addDevicePro(List<EntityTypePro> proList, Device device, String creatorId) {        String date = DateUtil.getTimeString();        for (EntityTypePro entpPro : proList) {            EntityPro enPro = new EntityPro();            enPro.setDeviceId(device.getDeviceId());            enPro.setEntityTypeId(device.getEntityTypeId());            enPro.setDevicePropertyId(UniqueUtil.uuid16());            enPro.setCreator(creatorId);            enPro.setCreateTime(date);            enPro.setEntpPropertyId(entpPro.getDevicePropertyId());            enPro.setPropertyName(entpPro.getPropertyName());            enPro.setPropertyType(entpPro.getPropertyType());            enPro.setPropertyUnit(entpPro.getPropertyUnit());            enPro.setPropertyValue(entpPro.getPropertyValue());            enPro.setStatus(entpPro.getStatus());            entityProMapper.insertSelective(enPro);        }    }    /**     * 添加设备属性     *     * @param entityPro     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> addDevicePro(EntityPro entityPro, EmployeeVo employee) throws Exception {        Map<String, Object> map = new HashMap<>();        String creatorId = employee.getEmployeeId();        String data = DateUtil.getTimeString();        entityPro.setDevicePropertyId(UniqueUtil.uuid16());        entityPro.setCreator(creatorId);        entityPro.setCreateTime(data);        map = validatePro(entityPro);        if ((Boolean) map.get("state") == false) return map;        int num = entityProMapper.insertSelective(entityPro);        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_true.code());        map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);        return map;    }    /**     * 修改设备属性     *     * @param entityPro     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> modifyDevicePro(EntityPro entityPro, EmployeeVo employee) throws Exception {        String modifyId = employee.getEmployeeId();        Map<String, Object> map = new HashMap<>();        map = validatePro(entityPro);        entityPro.setModifyer(modifyId);        entityPro.setModifyTime(DateUtil.getTimeString());        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;        int num = entityProMapper.updateByPrimaryKeySelective(entityPro);        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_true.code());        map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);        return map;    }    /**     * 批量删除特性     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceProById(String[] deviceProIds) throws Exception {        List<String> idss = new ArrayList<>();        //数组转换为list        if (deviceProIds != null && deviceProIds.length > 0) {            idss = Arrays.asList(deviceProIds);        }        Map<String, Object> map = new HashMap<>();        if (entityProMapper.delByDeviceProIds(idss) > 0) {            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.DEL_OK);            return map;        }        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        map.put("msg", BackMessage.DEL_FAIL);        return map;    }    /**     * 删除单一特性     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceProById(String deviceProIds) throws Exception {        Map<String, Object> map = new HashMap<>();        if (entityProMapper.delByDeviceProId(deviceProIds) > 0) {            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());            map.put("msg", BackMessage.DEL_OK);            return map;        }        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        map.put("msg", BackMessage.DEL_FAIL);        return map;    }    /**     * 导入特性表     *     * @param excel     * @param deviceId     * @return     * @throws Exception     *///    @Override//    @Transactional(propagation = Propagation.REQUIRED)//    public Map<String, Object> importDevicePro(MultipartFile excel, String deviceId, EmployeeVo employee) throws Exception {//        String creatorId = employee.getEmployeeId();//        Map<String, Object> map = new HashMap<>();//        if (excel.isEmpty()) {//            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());//            map.put("msg", BackMessage.UPLOAD_PLEASE);//            return map;//        }//        //解析EXCEL文件//        ExcelUtil eu = new ExcelUtil(EntityPro.class);//        String suffix = excel.getOriginalFilename().substring(excel.getOriginalFilename().lastIndexOf(".") + 1);//获取上传后缀//        List<EntityPro> enProList = eu.importExcel(excel.getInputStream(), suffix);//        String date = DateUtil.getTimeString();//        int num = 0;//        for (int i = 0; i < enProList.size(); i++) {//            EntityPro enPro = enProList.get(i);//            map = validatePro(enPro);//            if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {//                return map;//            }//            enPro.setDevicePropertyId(UniqueUtil.uuid16());//            enPro.setDeviceId(deviceId);//            enPro.setCreator(creatorId);//            enPro.setCreateTime(date);//            num += entityProMapper.insertSelective(enPro);//        }//        if (num > 0) {//            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());//            map.put("msg", BackMessage.IMPORT_OK);//            return map;//        }//        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("msg", BackMessage.IMPORT_FAIL);//        return map;//    }    /**     * 对特性参数进行校验     *     * @param enPro     * @return     */    private Map<String, Object> validatePro(EntityPro enPro) {        Map<String, Object> map = new HashMap<>();        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        if (StringUtils.isBlank(enPro.getPropertyName())) {            map.put("msg", "特性名称不能为空！");            return map;        }        if (enPro.getPropertyName().length() > 100) {            map.put("msg", "特性名称长度超过100字符！");            return map;        }        if (StringUtils.isBlank(enPro.getEntityTypeId())) {            map.put("msg", enPro.getPropertyName() + "特性类别不能为空！");            return map;        }        if (enPro.getEntityTypeId().matches("/^[1-3]$/")) {            map.put("msg", enPro.getPropertyName() + "特性类别格式不正确！");            return map;        }        if (enPro.getPropertyUnit() != null && enPro.getPropertyUnit().length() > 100) {            map.put("msg", enPro.getPropertyName() + "特性单位长度不能超过100字符！");            return map;        }        if (StringUtils.isBlank(enPro.getPropertyValue())) {            map.put("msg", enPro.getPropertyName() + "特性值不能为空！");            return map;        }        if (enPro.getPropertyValue().length() > 100) {            map.put("msg", enPro.getPropertyName() + "特性值长度不能超过100字符！");            return map;        }        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());        return map;    }    /*    -----------------------------以下为设备阈值操作方法--------------------------------------------------------------------------------------     */    /**     * 获取设备阈值     *     * @param deviceThreshold     * @return     *///    @Override//    public Map<String, Object> getDeviceThres(DeviceThreshold deviceThreshold) throws Exception {//        Map<String, Object> map = new HashMap<>();//        //添加分页查询条件//        if (deviceThreshold.getOffset() == null) deviceThreshold.setOffset(0);//        if (deviceThreshold.getLimit() == null) deviceThreshold.setLimit(10);//        List<DeviceThreshold> thresList = thresholdMapper.selectByThreshold(deviceThreshold);//        Integer total = thresholdMapper.selectCountByThreshold(deviceThreshold);//        if (thresList != null && thresList.size() > 0) {//            map.put("total", total);//            map.put("rows", thresList);//            return map;//        }//        return map;//    }    /**     * 添加设备阈值     *     * @param deviceThreshold     * @return     * @throws Exception     *///    @Override//    @Transactional(propagation = Propagation.REQUIRED)//    public Map<String, Object> addDeviceThres(DeviceThreshold deviceThreshold, EmployeeVo employee) throws Exception {//        Map<String, Object> map = new HashMap<>();//        String creatorId = employee.getEmployeeId();//        deviceThreshold.setCreateUserId(creatorId);//        deviceThreshold.setEntityThresholdId(UniqueUtil.uuid());//        deviceThreshold.setCreateTime(DateUtil.getTimeString());//        //对阈值编码进行判空并设置自动编码//        if (StringUtils.isBlank(deviceThreshold.getEntityThresholdCode())) {//            deviceThreshold.setEntityThresholdCode(getAutoCode());//        }//        map = validateThres(deviceThreshold);//        if ((Boolean) map.get("state") == false) return map;//        int num = thresholdMapper.insertSelective(deviceThreshold);//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);//        return map;//    }    /**     * 修改设备阈值     *     * @param deviceThreshold     * @return     * @throws Exception     *///    @Override//    @Transactional(propagation = Propagation.REQUIRED)//    public Map<String, Object> modifyDeviceThres(DeviceThreshold deviceThreshold, EmployeeVo employee) throws Exception {//        Map<String, Object> map = new HashMap<>();//        String modifierId = employee.getEmployeeId();//        map = validateThres(deviceThreshold);//        if ((Boolean) map.get("state") == false) return map;//        deviceThreshold.setUpdateUserId(modifierId);//        deviceThreshold.setUpdateTime(DateUtil.getTimeString());//        int num = thresholdMapper.updateByPrimaryKeySelective(deviceThreshold);//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);//        return map;//    }    /**     * 导入设备阈值     *     * @param excel     * @param deviceId     * @return     * @throws Exception     *///    @Override//    @Transactional(propagation = Propagation.REQUIRED)//    public Map<String, Object> importDeviceThres(MultipartFile excel, String deviceId, EmployeeVo employee) throws Exception {//        Map<String, Object> map = new HashMap<>();//        String creatorId = employee.getEmployeeId();//        if (excel.isEmpty()) {//            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());//            map.put("msg", BackMessage.UPLOAD_PLEASE);//            return map;//        }//        //解析EXCEL文件//        ExcelUtil eu = new ExcelUtil(DeviceThreshold.class);//        String suffix = excel.getOriginalFilename().substring(excel.getOriginalFilename().lastIndexOf(".") + 1);//获取上传后缀//        List<DeviceThreshold> objList = eu.importExcel(excel.getInputStream(), suffix);//        String date = DateUtil.getTimeString();//        int num = 0;//        for (DeviceThreshold threshold : objList) {//            threshold.setEntityThresholdId(UniqueUtil.uuid());//            threshold.setDeviceId(deviceId);//            threshold.setCreateUserId(creatorId);//            threshold.setCreateTime(date);//            threshold.setEntityThresholdCode(getAutoCode());//            map = validateThres(threshold);//            if ((Boolean) map.get("state") == false) return map;//            num += thresholdMapper.insertSelective(threshold);//        }//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.IMPORT_OK : BackMessage.IMPORT_FAIL);//        return map;//    }    /**     * 导入实体阈值     *     * @param excel     * @param entityId     * @return     * @throws Exception     *///    @Override//    public Map<String, Object> importEntityThres(MultipartFile excel, String entityId, EmployeeVo employee) throws Exception {//        Map<String, Object> map = new HashMap<>();//        String creatorId = employee.getEmployeeId();//        if (excel.isEmpty()) {//            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());//            map.put("msg", BackMessage.UPLOAD_PLEASE);//            return map;//        }//        //解析EXCEL文件//        ExcelUtil eu = new ExcelUtil(DeviceThreshold.class);//        String suffix = excel.getOriginalFilename().substring(excel.getOriginalFilename().lastIndexOf(".") + 1);//获取上传后缀//        List<DeviceThreshold> objList = eu.importExcel(excel.getInputStream(), suffix);//        String date = DateUtil.getTimeString();//        int num = 0;//        for (DeviceThreshold threshold : objList) {//            threshold.setEntityThresholdId(UniqueUtil.uuid());//            threshold.setEntityId(entityId);//            threshold.setCreateUserId(creatorId);//            threshold.setCreateTime(date);//            threshold.setEntityThresholdCode(getAutoCode());//            map = validateThres(threshold);//            if ((Boolean) map.get("state") == false) return map;//            num += thresholdMapper.insertSelective(threshold);//        }//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.IMPORT_OK : BackMessage.IMPORT_FAIL);//        return map;//    }    /**     * 按ID删除设备阈值     *     * @param etId     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceThresById(String etId) throws Exception {//        Map<String, Object> map = new HashMap<>();//        int num = thresholdMapper.updateStatus(etId);//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.DEL_OK : BackMessage.DEL_FAIL);        return null;    }    /**     * 批量删除设备阈值     *     * @param etIds     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> delDeviceThresById(String[] etIds) throws Exception {//        List<String> etIdList = new ArrayList<>();//        if (etIds != null && etIds.length > 0) {//            etIdList = Arrays.asList(etIds);//        }//        Map<String, Object> map = new HashMap<>();//        int num = thresholdMapper.updateStatusBatch(etIdList);//        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());//        map.put("result", num > 0 ? BackMessage.DEL_OK : BackMessage.DEL_FAIL);        return null;    }    /**     * 批量修改同步设备信息     *     * @param orgId     * @param enTypeId     * @param deviceIds     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> modifySycnDevice(String orgId, String enTypeId, String[] deviceIds, EmployeeVo employee) throws Exception {        Map<String, Object> map = new HashMap<>();        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());        //获取登录者信息        String modifierId = employee.getEmployeeId();        if (StringUtils.isBlank(enTypeId)) {            map.put("msg", "请选择设备类型");            return map;        }        if (deviceIds.length == 0) {            map.put("msg", "请选择需要修改的设备！");            return map;        }        /**         * 克隆实体特性         */        for (String deviceId : deviceIds) {            clonePro(deviceId, employee);        }        List<String> idList = Arrays.asList(deviceIds);        map.put("orgId", orgId);        map.put("enTypeId", enTypeId);        map.put("deviceIds", idList);        map.put("modifierId", modifierId);        map.put("modifyTime", DateUtil.getTimeString());        int num = deviceMapper.updateSycnDevice(map);        //设置返回信息        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());        map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);        return map;    }    /**     * 得到设备     *     * @param id     * @return     */    @Override    public Device getDeviceByDeviceId(String id) {        return deviceMapper.selectByDeviceId(id);    }    /**     * 导入设备信息和设备的拓展信息     *     * @param device     * @param deviceExpand     * @return     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public int importDevice(Device device, DeviceExpand deviceExpand, EmployeeVo employee) {        String creatorId = employee.getEmployeeId();        String date = DateUtil.getTimeString();        device.setDeviceId(UniqueUtil.uuid());        device.setCreateId(creatorId);        device.setModifyId(creatorId);        device.setCreateTime(date);        device.setModifyTime(date);        deviceMapper.insert(device);        deviceExpand.setDeviceExpandId(device.getDeviceId());        int count = deviceExpandMapper.insert(deviceExpand);        return count;    }    /**     * 获取设备树     *     * @param isOrg 判断是否为组织     * @param id     * @throws Exception     */    @Override    public List<Ztree> getDeviceTree(String isOrg, String id, Employee employee) throws Exception {       /* List<Ztree> ztList = new ArrayList<>();        if (StringUtils.isBlank(isOrg) && StringUtils.isBlank(id)) {            Employee employee = employeeService.getLoginEmployee();            Organization organization = organizationService.selectOrgByOrgId(employee.getOrgId());            List<Organization> organizationList = new ArrayList<>();            organizationList.add(organization) ;            ztList.addAll(getOrgZtreeList(organizationList));            //ztList.addAll(getOrgZtreeList(orgMapper.selectOrgByLevel("3")));            //如果当前是实体，按上级实体ID，查询下级实体        } else if (StringUtils.isNotBlank(isOrg) && !"1".equals(isOrg) && !StringUtils.isBlank(id)) {            ztList.addAll(getDeviceZtreeList(deviceMapper.selectByPEId(id)));            //如果当前是机构，按机构ID查询下级的机构及实体并转换为Ztree        } else if (StringUtils.isNotBlank(isOrg) && "1".equals(isOrg) && !StringUtils.isBlank(id)) {            ztList.addAll(getOrgZtreeList(orgMapper.selectOrgByOrgPId(id)));            ztList.addAll(getDeviceZtreeList(deviceMapper.selectByPOId(id)));        }        return ztList;*/        List<Ztree> list = entityService.getEntityTree(isOrg, id, employee);        return list;    }    /**     * 改变设备运行状态     *     * @param deviceId     * @param state     * @return     * @throws Exception     */    @Override    @Transactional(propagation = Propagation.REQUIRED)    public Map<String, Object> changeState(String deviceId, Integer state) throws Exception {        Map<String, Object> result = Maps.newHashMap();        result.put("state", RespCodeEnum.RESP_CODE_ENUM_false);        result.put("msg", BackMessage.ADD_FAIL);        Device device = new Device();        device.setDeviceId(deviceId);        device.setModifyTime(DateUtil.getTimeString());        device.setState(state + "");        if (DeviceStateEnum.ING.getCode() == state) {//设备启用            device.setInUseTime(DateUtil.getTimeString());        } else if (DeviceStateEnum.STOP.getCode() == state) {//设备停用            device.setDownTime(DateUtil.getTimeString());        }        int modifyCount = deviceMapper.update(device);        if (modifyCount > 0) {            DeviceRecord deviceRecord = new DeviceRecord();            deviceRecord.setDeviceId(deviceId);            deviceRecord.setState(new BigDecimal(state));            deviceRecord.setDeviceRecordId(UniqueUtil.uuid());            deviceRecord.setRecordTime(DateUtil.getTimeString());            deviceRecord.setStatus(new BigDecimal(0));            int insertCont = deviceRecordMapper.insertSelective(deviceRecord);            if (insertCont > 0) {                if (DeviceStateEnum.ING.getCode() == state) {//设备启用                    CycleCalculation(device);                }                result.put("state", RespCodeEnum.RESP_CODE_ENUM_true);                result.put("msg", BackMessage.ADD_OK);            }        }        return result;    }    /**     * 得到设备对应的隐患     *     * @param problem     * @return     *///    @Override//    public Map<String, Object> findProblemOfDeviceByPage(Problem problem) {//        Map<String, Object> map = new HashMap<>();//        return map;//    }    /**     * 将设备转换为树     *     * @param dvList     * @return     * @throws Exception     */    private List<Ztree> getDeviceZtreeList(List<DeviceVO> dvList) throws Exception {        List<Ztree> tree = new ArrayList<Ztree>();        for (DeviceVO device : dvList) {            Ztree enTree = new Ztree();            enTree.setId(device.getDeviceId());            enTree.setName(device.getDeviceName());            enTree.setOpen(RespCodeEnum.RESP_CODE_ENUM_false.code());            enTree.setIsEntity(1);            enTree.setIconSkin(TreeIconSkin.ICON_ENTITY.getDesc());            enTree.setIsParent(deviceMapper.selectCountByPid(device.getDeviceId()) > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());            if (StringUtils.isNotEmpty(device.getParentDeviceId())) {                enTree.setpId(device.getParentDeviceId());            } else if (StringUtils.isNotEmpty(device.getOrgId())) {                enTree.setpId(device.getOrgId());            }            tree.add(enTree);        }        return tree;    }    /**     * 将组织机构列表转换为树结构     *     * @param orgList     * @return     * @throws Exception     */    private List<Ztree> getOrgZtreeList(List<Organization> orgList) throws Exception {        List<Ztree> tree = new ArrayList<Ztree>();        for (Organization org : orgList) {            Ztree demo = new Ztree();            demo.setId(org.getOrgId());            demo.setpId(org.getParentOrgId());            demo.setName(org.getOrgName());            demo.setOrgLevel(org.getOrgLevelId());            demo.setIsOrg(1);            if ("1".equals(org.getOrgLevelId())) {                demo.setIconSkin(TreeIconSkin.ICON_BUIDING.getDesc());            }            if ("2".equals(org.getOrgLevelId())) {                demo.setIconSkin(TreeIconSkin.ICON_FLAG.getDesc());            }            if ("3".equals(org.getOrgLevelId())) {                demo.setIconSkin(TreeIconSkin.ICON_OA.getDesc());                demo.setOpen(RespCodeEnum.RESP_CODE_ENUM_false.code());            }            if ("4".equals(org.getOrgLevelId())) {                demo.setIconSkin(TreeIconSkin.ICON_STATION.getDesc());                demo.setOpen(RespCodeEnum.RESP_CODE_ENUM_false.code());            }            if ("5".equals(org.getOrgLevelId())) {                demo.setIconSkin(TreeIconSkin.IONC_WELL.getDesc());                demo.setOpen(RespCodeEnum.RESP_CODE_ENUM_false.code());            }            int orgNum = 0;            if (Integer.parseInt(org.getOrgLevelId()) < 4) {                orgNum = orgMapper.selectCountByPOId(org.getOrgId());            }            //判断是否含有下属设备，含有则为true，没有则为RespCodeEnum.RESP_CODE_ENUM_false.code()            // boolean isParent = deviceMapper.selectCountByPOId(org.getOrgId()) > 0 || orgNum > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code();            demo.setIsParent(true);            tree.add(demo);        }        return tree;    }    /**     * 阈值参数校验方法     *     * @param threshold     * @return     *///    private Map<String, Object> validateThres(DeviceThreshold threshold) {//        Map<String, Object> map = new HashMap<>();//        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());//        //判断阈值名称//        if (StringUtils.isBlank(threshold.getEntityThresholdName())) {//            map.put("msg", "阈值名称不能为空！");//            return map;//        }//        //判断阈值名称长度//        if (threshold.getEntityThresholdName().length() > 100) {//            map.put("msg", "阈值名称长度为100以内！");//            return map;//        }//        //判断阈值值的长度//        if (threshold.getThresHoldValue().length() > 100) {//            map.put("msg", "阈值值长度为100以内！");//            return map;//        }//        //判断阈值单位的长度//        if (threshold.getUnit().length() > 10) {//            map.put("msg", "阈值单位长度为10以内！");//            return map;//        }//        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());//        return map;//    }    /**     * 获取日期+时间+4位随机数自动编码     *     * @return     */    private String getAutoCode() {        String timestring = DateUtil.getTimeString().replace("-", "");        timestring = timestring.replace(":", "");        timestring = timestring.replace(" ", "");        return timestring + "_" + (new Random().nextInt(9000) + 1000);    }    /**     * 计算维护保养时间     *     * @param device     * @return     */    public int CycleCalculation(Device device) throws Exception {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");        DeviceMaintenance dm = new DeviceMaintenance();        String[] deviceArr = device.getDeviceId().split(",");        int num = 0;        for (String str : deviceArr) {            Device devices = new Device();            devices.setDeviceId(str);            DeviceVO deviceVO = deviceMapper.selectByDeviceId(str);            List<Long> longList = new ArrayList<>();            dm.setDeviceId(deviceVO.getDeviceId());            String isDate;            if (deviceVO.getMaintenanceNearTime() != null && !deviceVO.getMaintenanceNearTime().equals("")) {                isDate = deviceVO.getMaintenanceNearTime();            } else {                isDate = deviceVO.getInUseTime() + " 00:00";            }            Long datetime = null;            List<DeviceMaintenance> dmList = jsmDeviceMaintenanceService.getDeviceMaintenanceList(dm);            if (dmList.size() > 0 && dmList != null) {                Calendar c = Calendar.getInstance();                for (DeviceMaintenance dmt : dmList) {                    if (dmt.getMaintenanceName().equals("2")) {                        c.setTime(sdf.parse(isDate));   //设置当前日期                        c.add(Calendar.DATE, Integer.parseInt(dmt.getMaintenancePv().toString())); //日期加天                    } else {                        c.setTime(sdf.parse(isDate));   //设置当前日期                        c.add(Calendar.MONTH, Integer.parseInt(dmt.getMaintenancePv().toString())); //日期加天                    }                    longList.add(c.getTime().getTime());                }                for (int i = 0; i < longList.size(); i++) {                    if (longList.get(i) <= longList.get(0)) {                        datetime = longList.get(i);                    }                }                Date date = new Date(datetime);                System.out.println(sdf.format(date));                if (deviceArr.length > 1) {                    deviceVO.setMaintenanceNearTime(sdf.format(new Date()));                }                devices.setMaintenanceNextTime(sdf.format(date));            }            try {                num = deviceMapper.update(devices);            } catch (Exception e) {                e.printStackTrace();            }        }        return num;    }    /**     * @param clientDatas 客户端来的数据     * @return 服务端返回数据问题     */    @Override    public List<DeviceDataModel> getHttpServiceDatasByOpcs(List<DeviceDataModel> clientDatas) throws Exception {        Map<String, OpcModel> resMap = new HashMap<>();        List<DeviceDataModel> serviceDatas = new ArrayList<>();        List<String> stringList = new ArrayList<>();        if (clientDatas != null && clientDatas.size() > 0) {            for (DeviceDataModel ddm : clientDatas) {                stringList.add(ddm.getId());            }        }        // 调用接口返回数据        if (stringList != null && stringList.size() > 0) {            // 进行数据转换            resMap = getHttpService(stringList);        }        if (clientDatas != null && clientDatas.size() > 0) {            for (DeviceDataModel ddm : clientDatas) {                if (StringUtils.isNotEmpty(ddm.getId())) {                    OpcModel omd = resMap.get(ddm.getId());                    if (omd != null && omd.getValue() != null) {                        try {                            ddm.setValue(Float.parseFloat(omd.getValue()));                        } catch (NumberFormatException e) {                            ddm.setValue(Float.parseFloat("-1"));                        }                    }                }                serviceDatas.add(ddm);            }        }        return serviceDatas;    }    /**     * 得到设备对应的工单     *     * @param manageWorkOrderVo     * @return     */    @Override    public Map<String, Object> getWorkOrder(ManageWorkOrderVo manageWorkOrderVo) {        Map<String, Object> result = Maps.newHashMap();        result.put("rows", deviceMapper.getWorkOrderByDeviceId(manageWorkOrderVo));        result.put("total", deviceMapper.getWorkOrderByDeviceIdCount(manageWorkOrderVo));        return result;    }    /**     * 根据Opc采集点 获取到服务商的数据     *     * @param stringList     * @return     */    /**     * 根据Opc采集点 获取到服务商的数据     *     * @param stringList     * @return     */    private Map<String, OpcModel> getHttpService(List<String> stringList) {        Map<String, OpcModel> returnMap = new HashMap<>();        if (stringList != null && stringList.size() > 0) {        }        //  List<String> strList = JSONArray.parseArray(opcIds, String.class);        String sendData = "{\"itemName\":" + JSONArray.toJSON(stringList) + "}";        logger.info("---发送报文sendData-->" + sendData);        String returnStr = null;        try {            //处理连接超时            returnStr = HttpClientUtil.httpPostWithJson(configUril, sendData);            logger.info("---返回报文returnStr-->" + returnStr);        } catch (Exception e) {            return returnMap;        }        if (StringUtils.isNotEmpty(returnStr) && returnStr.contains("value")) {            JSONObject jsonObject = JSON.parseObject(returnStr);            String resValue = jsonObject.get("value").toString();            if (StringUtils.isNotEmpty(resValue)) {                logger.info("---返回报文数据正常resValue-->" + resValue);                List<Object> resValueStr = JSON.parseArray(resValue);                // 解析数据修改问题                if (resValueStr != null && resValueStr.size() > 0) {                    if (stringList.size() == 1) {                        // opc一条数据组合                        // opc 单个值的数据                        String opcId = resValueStr.get(0).toString();                        String value = resValueStr.get(1).toString();                        String status = resValueStr.get(2).toString();                        String dateTime = resValueStr.get(3).toString();                        OpcModel od = new OpcModel();                        od.setOpcId(opcId);                        od.setStatus(status);                        od.setValue(value);                        od.setDateTime(dateTime);                        returnMap.put(opcId, od);                    } else {                        for (Object object : resValueStr) {                            List<Object> dataObjs = JSON.parseArray(object.toString());                            String opcId = dataObjs.get(0).toString();                            String value = dataObjs.get(1).toString();                            String status = dataObjs.get(2).toString();                            String dateTime = dataObjs.get(3).toString();                            OpcModel od = new OpcModel();                            od.setOpcId(opcId);                            od.setStatus(status);                            od.setValue(value);                            od.setDateTime(dateTime);                            returnMap.put(opcId, od);                        }                    }                } else {                    logger.info("---返回报文数据错误--数据为空resValue-->" + resValue);  // 报文数据格式不正确                }            } else {                logger.info("---返回报文数据错误--数据为空-->" + returnStr);  // 报文数据格式不正确            }        } else {            logger.info("---返回报文-->" + returnStr);  // 报文数据格式不正确        }        return returnMap;    }    /**     * @param organizationList 当前人所有的组织机构 不包含部门     * @param keyword          模糊搜索问题     */    @Override    public List<DeviceVO> queryDeviceVoByOrgsKeyword(List<Organization> organizationList, String keyword) throws Exception {        List<String> orgIds = new ArrayList<>();        Map resMap = new HashMap<>();        if (organizationList != null && organizationList.size() > 0) {            for (Organization organization : organizationList) {                orgIds.add(organization.getOrgId());            }        }        resMap.put("orgIds", orgIds);        resMap.put("keyword", keyword);        List<DeviceVO> deviceVOList = deviceMapper.queryDeviceVoByOrgsKeyword(resMap);        //        return deviceVOList;    }    @Override    public DeviceCountVo queryDeviceCount(DeviceCountVo deviceCountVo){       DeviceCountVo deviceCountVos =  deviceMapper.queryDeviceCount(deviceCountVo);        return deviceCountVos;    }    @Override    public List<DeviceVO> queryDeviceList(List<String> deviceList) {        return deviceMapper.queryDeviceList(deviceList);    }}